<template>
  <div class="login">
    <div class="flex-v login-root-div">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <div class="title">
          <img src="@/assets/logo/login_logo.png" alt="dark" />
        </div>

        <div class="input-title">手机号</div>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="请输入">
            <template #prefix>
              <el-icon size="20">
                <Iphone />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div v-if="!isCodeLogin" class="input-title" style="margin-top: 30px;">密码</div>
        <el-form-item v-if="!isCodeLogin" prop="password">
          <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="请输入"
            @keyup.enter="handleLogin">
            <template #prefix>
              <el-icon size="20">
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div v-if="isCodeLogin" class="input-title" style="margin-top: 30px;">验证码</div>
        <el-form-item prop="code" v-if="isCodeLogin">
          <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="请输入" @keyup.enter="handleLogin"
            maxlength="6">
            <template #prefix>
              <el-icon size="20">
                <Stopwatch />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <div class="flex-stb">
          <!-- <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox> -->
          <div class="change-txt" @click="isCodeLogin = !isCodeLogin">
            <el-icon size="16" color="#747474">
              <Refresh />
            </el-icon>
            <span style="margin-left: 5px">{{ isCodeLogin ? '账号密码登录' : '验证码登录' }}</span>
          </div>
          <div class="forget-pwd-txt">忘记密码 ? </div>
        </div>

        <el-form-item style="width:100%;margin-top: 40px;">
          <el-button :loading="loading" size="large" type="primary" class="op-btn" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>

        <div class="agree-div" @click="isAgree = !isAgree">
          <el-checkbox v-model="isAgree" label="" size="large" @change="changeAgreeStatus" />
          同意
          <span>《用户使用协议》</span>
          和
          <span>《隐私协议》</span>
        </div>
      </el-form>
    </div>

    <div class="el-login-footer">
      <span>Copyright © 2023 yuncst All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();
const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const isCodeLogin = ref(false);
const isAgree = ref(false);

const loginForm = ref({
  username: "super",
  password: "123",
  rememberMe: false,
  code: "",
  uuid: ""
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {
  if (!isAgree.value) {
    return proxy.$modal.msgError('请先阅读并勾选协议');
  }

  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }

      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur];
          }
          return acc;
        }, {});
        router.push({ path: redirect.value || "/", query: otherQueryParams });
        loading.value = false;

      }).catch(() => {
        loading.value = false;
      });
    }
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

getCookie();

const changeAgreeStatus = () => {
  isAgree.value = !isAgree.value
}

</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: 100% 100%;
}

.login-root-div {
  position: relative;
  width: 1188px;
  min-width: 1188px;
  height: 582px;
  background-image: url("../assets/images/login_form_bg.png");
  background-size: 100% 100%;
}

.title {
  margin: 30px auto 30px auto;
  text-align: center;
  color: #2A95F9;
  font-size: 32px;
  cursor: pointer;

  img {
    width: 270px;
  }
}

.login-form {
  position: absolute;
  top: 10px;
  right: 16px;
  z-index: 1;
  width: 40%;
  height: calc(100% - 30px);
  padding: 0 55px;
  border-radius: 0 17px 17px 0;
  background: #ffffff;

  .el-input {
    height: 50px;

    input {
      height: 50px;
    }
  }

  ::v-deep(.el-input__wrapper) {
    border-radius: 8px !important;
    box-shadow: 0 0 0 1px #D9D9D9 inset;
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

.input-title {
  color: #303030;
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 8px;
  font-family: Inter, Inter;
}

.change-txt {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #747474;
  cursor: pointer;
}

.forget-pwd-txt {
  color: #2A95F9;
  font-size: 14px;
  cursor: pointer;
}

.op-btn {
  width: 100%;
  height: 50px;
  font-size: 18px;
  background: #2A95F9;
}

.agree-div {
  color: #747474;
  font-size: 14px;
  text-align: center;
  cursor: pointer;

  span {
    color: #2A95F9;
  }
}
</style>
